#!/usr/bin/env bash

set -eu
script_name=$0
DB_BACKEND=$(echo "${script_name}" | cut -d- -f2)
export DB_BACKEND

die() {
    echo >&2 "$@"
    exit 1
}

MYSQL_HOST=${MYSQL_HOST:-127.0.0.1}
MYSQL_PORT=${MYSQL_PORT:-3306}
MYSQL_PASSWORD=${MYSQL_PASSWORD:-password}
MYSQL_USER=${MYSQL_USER:-root}

about() {
    die "usage: ${script_name} [ config_yaml | setup | dump <backup_file> | restore <backup_file> ]"
}

check_requirements() {
    if ! command -v mysql >/dev/null; then
        die "missing required program 'mysql' as a mysql client (package mariadb-client on debian like system)"
    fi
}

silence_password_warning() {
    ( ( ( "$@" >&9 ) 2>&1 \
        | grep -F -v "[Warning] Using a password on the command line interface can be insecure." ) >&2 ) 9>&1 || [[ $? == 1 ]]
}

exec_sql() {
    cmd="${1?Missing required sql command}"

    silence_password_warning \
        mysql \
        "--host=${MYSQL_HOST}" \
        "--user=${MYSQL_USER}" \
        "--port=${MYSQL_PORT}" \
        "--password=${MYSQL_PASSWORD}" <<< "${cmd}"
}

setup() {
    exec_sql "DROP DATABASE IF EXISTS crowdsec_test;"
    exec_sql "CREATE DATABASE crowdsec_test;"
    exec_sql "DROP USER IF EXISTS crowdsec_test;"
    exec_sql "CREATE USER 'crowdsec_test' IDENTIFIED BY 'crowdsec_test';"
    exec_sql "GRANT ALL PRIVILEGES ON crowdsec_test.* TO 'crowdsec_test';"
}

dump() {
    backup_file="${1?Missing file to backup database to}"

    args=(mysqldump)
    if mysqldump --column-statistics 2>&1 | grep -q -v 'unknown option'; then
        args+=("--column-statistics=0")
    fi
    args+=("--host=${MYSQL_HOST}" "--port=${MYSQL_PORT}" "--user=${MYSQL_USER}" "--password=${MYSQL_PASSWORD}" --databases crowdsec_test)

    silence_password_warning "${args[@]}" > "${backup_file}"
}

restore() {
    backup_file="${1?missing file to restore database from}"
    [[ -f "${backup_file}" ]] || die "Backup file ${backup_file} doesn't exist"

    # clear global transaction identifiers before restore
    exec_sql "RESET BINARY LOGS AND GTIDS;"

    silence_password_warning \
        mysql \
        "--host=${MYSQL_HOST}" \
        "--user=${MYSQL_USER}" \
        "--port=${MYSQL_PORT}" \
        "--password=${MYSQL_PASSWORD}" < "${backup_file}"

    exec_sql "DROP USER IF EXISTS 'crowdsec_test';"
    exec_sql "CREATE USER 'crowdsec_test' IDENTIFIED BY 'crowdsec_test';"
    exec_sql "GRANT ALL PRIVILEGES ON crowdsec_test.* TO 'crowdsec_test';"
}

config_yaml() {
    MYSQL_PORT=${MYSQL_PORT} MYSQL_HOST=${MYSQL_HOST} yq e '
        .db_config.type=strenv(DB_BACKEND)|
        .db_config.user="crowdsec_test" |
        .db_config.password="crowdsec_test" |
        .db_config.db_name="crowdsec_test"  |
        .db_config.host=strenv(MYSQL_HOST) |
        .db_config.port=env(MYSQL_PORT) |
        del(.db_config.db_path)
    ' -i "${CONFIG_YAML}"
}

[[ $# -lt 1 ]] && about

check_requirements

case "$1" in
    setup)
        setup
        ;;
    config-yaml)
        config_yaml
        ;;
    dump)
        shift
        dump "$@"
        ;;
    restore)
        shift
        restore "$@"
        ;;
    exec_sql)
        shift
        #
        # This command is meant to run a query against the the crowdsec database.
        # The exec_sql() function is more generic and is also used for database setup and backups.
        #
        # For this reason, we select the database here.
        #
        exec_sql "use crowdsec_test; $@"
        ;;
    *)
        about
        ;;
esac;
